import fs from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';
import ejs from 'ejs';
import { execSync } from 'child_process';

const __dirname = path.dirname(fileURLToPath(import.meta.url));

export function createProjectDirectory(projectName, targetDir) {
  const projectDir = path.join(targetDir, projectName);
  if (!fs.existsSync(projectDir)) {
    fs.mkdirSync(projectDir);
  }
  return projectDir;
}

export function getTemplateDir(projectType) {
  if (projectType === '微前端工程') {
    return path.join(__dirname, '../templates/vite-project');
  }
  return path.join(__dirname, '../templates/vite-vue');
}

export function getTargetDir(projectType, projectDir, projectName) {
  if (projectType === '微前端子工程') {
    const packagesDir = path.join(projectDir, 'packages');
    if (!fs.existsSync(packagesDir)) {
      console.error('错误：微前端子工程需要在项目的 packages 目录下创建，当前项目目录下不存在 packages 目录，请检查后重试。');
      throw new Error('微前端子工程创建失败：缺少 packages 目录');
    }
    const subProjectDir = path.join(packagesDir, projectName);
    if (!fs.existsSync(subProjectDir)) {
      fs.mkdirSync(subProjectDir);
    }
    return subProjectDir;
  }
  return projectDir;
}

export function handleLanguageChoice(answers, targetDir) {
  if (answers.template === 'Vite + TypeScript') {
    const mainJsPath = path.join(targetDir, 'src/main.js');
    if (fs.existsSync(mainJsPath)) {
      fs.renameSync(mainJsPath, path.join(targetDir, 'src/main.ts'));
    }

    function processDirectory(dir) {
      const items = fs.readdirSync(dir);
      for (const item of items) {
        const itemPath = path.join(dir, item);
        const stat = fs.statSync(itemPath);
        if (stat.isDirectory()) {
          processDirectory(itemPath);
        } else {
          if (path.extname(itemPath) === '.vue') {
            let content = fs.readFileSync(itemPath, 'utf8');
            content = content.replace('<script>', '<script lang="ts">');
            fs.writeFileSync(itemPath, content);
          }
        }
      }
    }

    processDirectory(targetDir);
  }
}

export function replaceProjectName(answers, projectDir, targetDir) {
  let pkgPath = path.join(projectDir, 'package.json');
  if (answers.projectType === '微前端子工程') {
    pkgPath = path.join(targetDir, 'package.json');
  }
  if (fs.existsSync(pkgPath)) {
    let pkgContent = fs.readFileSync(pkgPath, 'utf8');
    pkgContent = pkgContent.replace(/"name": ".*?"/, `"name": "${answers.projectName}"`);
    fs.writeFileSync(pkgPath, pkgContent);
  }
}

export function printSuccessMessage(projectName) {
  console.log(`\n项目 ${projectName} 创建成功！`);
  console.log(`cd ${projectName}`);
  console.log('npm install');
  console.log('npm run dev\n');
}